package com.xsm.activitygroup;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.umeng.analytics.MobclickAgent;
import com.xsm.DataBase.ReadMessage;
import com.xsm.DataBase.SaveMessage;
import com.xsm.activitygroup.R;
import com.xsm.internet.PostMessage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class Usermessage extends Activity{
	Context context;
	ArrayList<String> types;
	ArrayList<String> ms;
	static String user;
	ProgressBar bar;
GetUserMessage getUserMessage;
String message;
ImageView usericon;
String icon;
TextView usersex,usernick,Id,school,jindou,phone,signature,email;
Drawable icondraDrawable;
String sex,nick;
PullToRefreshScrollView pullToRefreshScrollView;
ArrayList<String> result;
LoadMessageHandler handler;
LinearLayout messageLayout;
private String FLAG="LOGINOUTUSER";
private RelativeLayout loadLayout,errorLayout;

protected void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.usermessage);
	context=this;
	handler=new LoadMessageHandler();
	SharedPreferences sharedPreferences=getSharedPreferences("XSM", 0);
	user=sharedPreferences.getString("User","");
	message=sharedPreferences.getString("userMessage", "");
	pullToRefreshScrollView=(PullToRefreshScrollView)findViewById(R.id.messageList);
	usericon=(ImageView)findViewById(R.id.usericon);
    usersex=(TextView)findViewById(R.id.sex);
    usernick=(TextView)findViewById(R.id.nick);
    Id=(TextView)findViewById(R.id.Id);
    school=(TextView)findViewById(R.id.school);
    jindou=(TextView)findViewById(R.id.jindou);
    phone=(TextView)findViewById(R.id.phone);
    signature=(TextView)findViewById(R.id.signature); 
    email=(TextView)findViewById(R.id.email);
     messageLayout=(LinearLayout)findViewById(R.id.messagelayout);
	loadLayout=(RelativeLayout)findViewById(R.id.loadlayout);
	errorLayout=(RelativeLayout)findViewById(R.id.errorlayout);
     bar=(ProgressBar)findViewById(R.id.bar);
	types=new ArrayList<String>();	
	ms=new ArrayList<String>();
  pullToRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
					DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			bar.setVisibility(View.VISIBLE);
		getUserMessage=new GetUserMessage();
		getUserMessage.execute();
		}
	});
  
messageLayout.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);

pullToRefreshScrollView.setVisibility(View.GONE);
new Thread(new Getold()).start();
}

public void Back(View view){
finish();	
}

public void Update(View view){
	messageLayout.setVisibility(View.GONE);
	loadLayout.setVisibility(View.VISIBLE);
	errorLayout.setVisibility(View.GONE);
	new Thread(new Getold()).start();	
}

class GetUserMessage extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... bg) {
		List params=new ArrayList();
		params.add(new BasicNameValuePair("ASK","GetMessage"));
		params.add(new BasicNameValuePair("user",user));
		PostMessage postMessage=new PostMessage(params);
		String result=postMessage.getResult();
		try {
			if(!result.equals("-1")){
			 JSONArray array=new JSONArray(result);
			JSONObject object=array.optJSONObject(0);
	          String level=object.getString("level");
	          String phone=object.getString("phone");
	          String school=object.getString("school");
	          String jindou=object.getString("jindou");
	          String signature=object.getString("signature");
	          String name=object.getString("name");
	          String sex=object.getString("sex");
	          String icon=object.getString("icon");
	          String email=object.getString("email");
	       ms.clear();   
	       ms.add(user);
	       int l=Integer.parseInt(level);
	       String lsString=(l/20)+"";
	       ms.add(lsString);
	       ms.add(name);
	       ms.add(sex);
	       ms.add(icon);
	       ms.add(school);
	       ms.add(jindou);
	       ms.add(phone);
	       ms.add(signature);
	       ms.add(email);
  icondraDrawable=loadImageFromNetwork(context,icon);   
SaveMessage save=new SaveMessage(context, user);
save.saveUserMessage(ms);	          
			}
			} catch (Exception e) {
	Log.d("my", e+"");			
			}				
		return result;
	}
	
	protected void onPostExecute(String result) {	
		pullToRefreshScrollView.setVisibility(View.VISIBLE);
		loadLayout.setVisibility(View.GONE);
        if(result.equals("-1")){
        errorLayout.setVisibility(View.VISIBLE);
        Toast.makeText(context,"连接服务器失败", Toast.LENGTH_LONG).show();
  }else {
Id.setText(ms.get(0));
usernick.setText(ms.get(2));
usersex.setText(ms.get(3));
if(icondraDrawable!=null)
usericon.setBackgroundDrawable(icondraDrawable);else {
	if(ms.get(3).equals("男")){
		usericon.setBackgroundResource(R.drawable.boy);
	}else if(ms.get(3).equals("女")){
		usericon.setBackgroundResource(R.drawable.girl);
	}else {
		usericon.setBackgroundResource(R.drawable.nosex);
	}
}
school.setText(ms.get(5));
jindou.setText(ms.get(6));
phone.setText(ms.get(7));
signature.setText(ms.get(8));
email.setText(ms.get(9));
messageLayout.setVisibility(View.VISIBLE);
}
 pullToRefreshScrollView.onRefreshComplete();
bar.setVisibility(View.GONE);
super.onPostExecute(result);
	}
}




protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==1){
int index=0;	
switch (resultCode) {
case RESULT_OK:
String type=data.getExtras().getString("type");
String value=data.getExtras().getString("value");
if(type.equals("name"))
index=2;
else if(type.equals("issuephone"))
index=5;
else if(type.equals("signature"))
index=6;
else if(type.equals("email")){
	index=7;
}

if(index==2){
usernick.setText(value);
ms.set(2,value);
}
else if(index==5){
phone.setText(value);	
ms.set(7,value);
}else if(index==6){
signature.setText(value);
ms.set(8,value);
}else if(index==7){
email.setText(value);
ms.set(9,value);
}
break;
default:
	break;
}
}else if(requestCode==2){
	if(resultCode==RESULT_OK){
	String value=data.getExtras().getString("result");
	ms.set(5, value);
	school.setText(value);}
}else if(requestCode==3){
	if(resultCode==RESULT_OK){
		String value=data.getExtras().getString("result");
		ms.set(3, value);
		usersex.setText(value);
		if(icondraDrawable==null){
			if(value.equals("男")){
				usericon.setBackgroundResource(R.drawable.boy);
			}else{
				usericon.setBackgroundResource(R.drawable.girl);
			}
		}
	}
}

}


protected void onDestroy() {
	  if (getUserMessage != null && getUserMessage.getStatus() != AsyncTask.Status.FINISHED)
		  getUserMessage.cancel(true);
	super.onDestroy();
}

@Override
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
@Override
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}


public static Drawable loadImageFromNetwork(Context context, String imageUrl)   
{   
    Drawable drawable = null;   
    if(imageUrl == null )   
        return null;   
    String imagePath = "";   
    String   fileName   = "";            
    // 获取url中图片的文件名与后缀   
    if(imageUrl!=null&&imageUrl.length()!=0){    
        fileName  = imageUrl.substring(imageUrl.lastIndexOf("/")+1);   
    }    
    // 图片在手机本地的存放路径,注意：fileName为空的情况   
    imagePath = context.getCacheDir() + "/" + user;   
    Log.i("test","imagePath = " + imagePath);   
    File file = new File(context.getCacheDir(),user);// 保存文件   
    Log.i("test","file.toString()=" + file.toString());   
    if(!file.exists()&&!file.isDirectory())   
    {   
        try {   
            // 可以在这里通过文件名来判断，是否本地有此图片   
               
            FileOutputStream   fos=new   FileOutputStream( file );   
            InputStream is = new URL(imageUrl).openStream();   
            int   data = is.read();    
            while(data!=-1){    
                    fos.write(data);    
                    data=is.read();;    
            }    
            fos.close();   
            is.close();   
//          drawable = Drawable.createFromStream(   
//                  new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent();   
            drawable = Drawable.createFromPath(file.toString());   
            Log.i("test", "file.exists()不文件存在，网上下载:" + drawable.toString());   
        } catch (IOException e) {   
            Log.d("test", e.getMessage());   
        }   
    }else  
    {   
        drawable = Drawable.createFromPath(file.toString());   
        Log.i("test", "file.exists()文件存在，本地获取");   
    }   
       
    if (drawable == null) {   
        Log.d("test", "null drawable");   
    } else {   
        Log.d("test", "not null drawable");   
    }   
       
    return drawable ;   
}


public void NickName(View view){
	Intent intent=new Intent();
	intent.setClass(context,EditMessage.class);
	intent.putExtra("type","name");
	intent.putExtra("value",ms.get(2));	
	startActivityForResult(intent, 1);
}
public void  Email(View view){
	Intent intent=new Intent();
	intent.setClass(context,EditMessage.class);
	intent.putExtra("type","email");
	intent.putExtra("value",ms.get(9));	
	startActivityForResult(intent, 1);
}

public void Changepass(View view){
	Intent intent=new Intent();
	intent.setClass(context,EditPassword.class);
	startActivityForResult(intent, 1);	
}

public void School(View view){
Intent intent=new Intent();
intent.putExtra("value",ms.get(5));
intent.putExtra("type","school");
intent.setClass(context, ChangeChose.class);
startActivityForResult(intent,2);
}

public void Sex(View view){
Intent intent=new Intent();
intent.putExtra("value",ms.get(3));
intent.putExtra("type","sex");
intent.setClass(context, ChangeChose.class);
startActivityForResult(intent,3);
}

public void Phone(View view){
	Intent intent=new Intent();
	intent.setClass(context,EditMessage.class);
	intent.putExtra("type","issuephone");
	intent.putExtra("value",ms.get(7));	
	startActivityForResult(intent, 1);
}

public void Signature(View view){
	Intent intent=new Intent();
	intent.setClass(context,EditMessage.class);
	intent.putExtra("type","signature");
	intent.putExtra("value",ms.get(8));	
	startActivityForResult(intent, 1);
}
public void LoginOut(View view){
	AlertDialog.Builder builder=new AlertDialog.Builder(context);
	builder.setTitle("提示");
	builder.setMessage("是否退出此账户?");
	builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			 dialog.dismiss();
			SharedPreferences sharedPreferences=getSharedPreferences("XSM", 0);
			sharedPreferences.edit().putString("User", "").commit();
			sharedPreferences.edit().putString("IsLogin", "").commit();
			Intent  intent=new Intent();
			intent.setClass(context, Login.class);
			startActivity(intent);
			
			Intent intent2 = new Intent();  //Itent就是我们要发送的内容
            intent2.putExtra("message","LoginOut");   
            intent2.setAction(FLAG);   //设置你这个广播的action，只有和这个action一样的接受者才能接受者才能接收广播
            sendBroadcast(intent2);   //发送广播        
			 finish();
		}
	})	;	
	builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
		}
	});
	builder.create().show();
}

class LoadMessageHandler extends Handler{
	public void handleMessage(Message msg) {
		if(msg.what==1){
			if(result.size()==0){
				getUserMessage=new GetUserMessage();
				getUserMessage.execute();			
				}else{
					ms.clear();
					for(int i=0;i<result.size();i++){
						ms.add(result.get(i));
						Log.d("my", result.get(i));	
					}
				loadLayout.setVisibility(View.GONE);
				pullToRefreshScrollView.setVisibility(View.VISIBLE);
				if(icondraDrawable!=null)
					usericon.setBackgroundDrawable(icondraDrawable);
				    else {
						if(ms.get(3).equals("男")){
							usericon.setBackgroundResource(R.drawable.boy);
						}else if(ms.get(3).equals("女")){
							usericon.setBackgroundResource(R.drawable.girl);
						}else {
							usericon.setBackgroundResource(R.drawable.nosex);
						}
						}
				Id.setText(ms.get(0));
				usernick.setText(ms.get(2));
				usersex.setText(ms.get(3));
				school.setText(ms.get(5));
				jindou.setText(ms.get(6));
				phone.setText(ms.get(7));
				signature.setText(ms.get(8));
				email.setText(ms.get(9));
				messageLayout.setVisibility(View.VISIBLE);
				}
		}
	}
}

class Getold implements Runnable{
	public void run() {
		ReadMessage readMessage=new ReadMessage(context, user);
		 result=readMessage.getMessage();
		 if(result.size()>0)
	     icondraDrawable=loadImageFromNetwork(context,result.get(4));  
		 Message msg=handler.obtainMessage();
		 msg.what=1;
		 handler.sendMessage(msg);
	}
}

}
